/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * @author 品讯科技
 */

package com.px.pa.modulars.circle.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pig.common.core.util.R;
import com.px.basic.alone.security.annotation.Inner;
import com.px.basic.alone.security.util.SecurityUtils;
import com.px.fastfile.service.FastfileService;
import com.px.pa.modulars.circle.entity.CircleMeetingSign;
import com.px.pa.modulars.circle.entity.CircleWxInfo;
import com.px.pa.modulars.circle.entity.CricleMeeting;
import com.px.pa.modulars.circle.service.CircleMeetingSignService;
import com.px.pa.modulars.circle.service.CircleWxInfoService;
import com.px.pa.modulars.circle.service.CricleMeetingService;
import com.px.pa.modulars.upms.entity.SysUser;
import com.px.pa.modulars.upms.service.SysUserService;
import com.px.pa.modulars.utils.WxQr;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * @author 品讯科技
 * @date 2024-08
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/criclemeeting")
@Api(value = "criclemeeting", tags = "管理")
public class CricleMeetingController {

    private final CricleMeetingService cricleMeetingService;
    private final CircleMeetingSignService circleMeetingSignService;
    private final SysUserService sysUserService;
    private final CircleWxInfoService circleWxInfoService;
    @Autowired
    protected HttpServletRequest request;
    @Autowired
    private FastfileService fastfileService;


    private SysUser getUser(){
        SysUser user = sysUserService.getById(SecurityUtils.getUser().getId());
        return user;
    }
    /**
     * 分页查询
     *
     * @param page          分页对象
     * @param cricleMeeting
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page")
    @PreAuthorize("@pms.hasPermission('circleMeeting_criclemeeting_get')")
    public R getCricleMeetingPage(Page page, CricleMeeting cricleMeeting) {
        Page<CricleMeeting> cricleMeetingPage = cricleMeetingService.page(page, new QueryWrapper<CricleMeeting>()
                .eq("tenant_code",getUser().getOnlyLogo())
                .eq("enable",1)
                .between(cricleMeeting.getStartTime() != null && cricleMeeting.getEndTime() != null,
                        "sign_time", cricleMeeting.getStartTime(), cricleMeeting.getEndTime()));
        cricleMeetingPage.getRecords().forEach(cricleMeeting1 -> {
          int count =  circleMeetingSignService.count(new QueryWrapper<CircleMeetingSign>().eq("meeting_id",cricleMeeting1.getId()));
          int countSign =  circleMeetingSignService.count(new QueryWrapper<CircleMeetingSign>()
                    .eq("meeting_id",cricleMeeting1.getId()).eq("is_sign",1));//是否签到（1.已签到2.未签到）
            cricleMeeting1.setSignSum(count);
            cricleMeeting1.setSignNum(countSign);
            if(cricleMeeting1.getCreateBy() != null){
              SysUser sysUser = sysUserService.getById(cricleMeeting1.getCreateBy());
                cricleMeeting1.setCreateByName(sysUser.getName());
            }
           Map<String, Object> map = cricleMeetingService.getNameByids(cricleMeeting1.getId());
            if(map.size()>0){
                cricleMeeting1.setSignPeopleName(map.get("name").toString());
            }

        });
        return R.ok(cricleMeetingPage);
    }


    /**
     * 通过id查询
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('circleMeeting_criclemeeting_get')")
    public R getById(@PathVariable("id") Integer id) {
        CricleMeeting circleMeeting =  cricleMeetingService.getById(id);
        Map<String, Object> map = cricleMeetingService.getNameByids(circleMeeting.getId());
        if(map.size()>0){
            circleMeeting.setSignPeopleName(map.get("name").toString());
        }
        int count =  circleMeetingSignService.count(new QueryWrapper<CircleMeetingSign>()
                .eq("meeting_id",circleMeeting.getId()));
        int countSign =  circleMeetingSignService.count(new QueryWrapper<CircleMeetingSign>()
                .eq("meeting_id",circleMeeting.getId()).eq("is_sign",1));//是否签到（1.已签到2.未签到）
        circleMeeting.setSignSum(count);
        circleMeeting.setSignNum(countSign);
        return R.ok(circleMeeting);
    }

    /**
     * 新增
     *
     * @param cricleMeeting
     * @return R
     */
    @ApiOperation(value = "新增", notes = "新增")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('circleMeeting_criclemeeting_add')")
    public R save(@RequestBody CricleMeeting cricleMeeting) {

        SysUser user  = getUser();
//        Integer userId = SecurityUtils.getUser().getId();
        cricleMeeting.setEnable(1);
        cricleMeeting.setCreateBy(user.getUserId());
        cricleMeeting.setCreateTime(LocalDateTime.now());
        cricleMeeting.setTenantCode(user.getOnlyLogo());
        cricleMeetingService.save(cricleMeeting);
        List<Integer> list = new ArrayList<>();
        list = cricleMeeting.getUids();
          list.forEach(a->{
              CircleMeetingSign circleMeetingSign = new CircleMeetingSign();
              circleMeetingSign.setMeetingId(cricleMeeting.getId());
              circleMeetingSign.setIsSign(2);
              circleMeetingSign.setUid(a);
              circleMeetingSign.setCreateTime(LocalDateTime.now());
              circleMeetingSign.setEnable(1);
              circleMeetingSignService.save(circleMeetingSign);
          });
        return R.ok();
    }

    /**
     * 修改
     *
     * @param cricleMeeting
     * @return R
     */
    @ApiOperation(value = "修改", notes = "修改")
    @PutMapping
    @PreAuthorize("@pms.hasPermission('circleMeeting_criclemeeting_edit')")
    public R updateById(@RequestBody CricleMeeting cricleMeeting) {

        cricleMeetingService.updateById(cricleMeeting);
        List<Integer> list = new ArrayList<>();
        list = cricleMeeting.getUids();
        list.forEach(a->{
           int count = circleMeetingSignService.count(new QueryWrapper<CircleMeetingSign>().eq("uid",a).eq("meeting_id",cricleMeeting.getId()));
           if(count ==0){
               CircleMeetingSign circleMeetingSign = new CircleMeetingSign();
               circleMeetingSign.setMeetingId(cricleMeeting.getId());
               circleMeetingSign.setIsSign(2);
               circleMeetingSign.setUid(a);
               circleMeetingSign.setCreateTime(LocalDateTime.now());
               circleMeetingSign.setEnable(1);
               circleMeetingSignService.save(circleMeetingSign);
           }
        });
        return R.ok();
    }

    /**
     * 通过id删除
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除", notes = "通过id删除")
    @DeleteMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('circleMeeting_criclemeeting_del')")
    public R removeById(@PathVariable Integer id) {
        CricleMeeting cricleMeeting =  cricleMeetingService.getById(id);
        cricleMeeting.setEnable(2); //是否被删除（1.正常2.已被删除）
        return R.ok(cricleMeetingService.updateById(cricleMeeting));
    }

    /**
     * 签到二维码
     *
     * @param
     * @param
     * @return
     */
    @ApiOperation(value = "签到二维码", notes = "签到二维码")
    @GetMapping("/sign/qr")
    public R getDetails(@RequestParam("id") Integer id) {
        SysUser user = getUser();
        String tenant = user.getOnlyLogo();
        CircleWxInfo circleWxInfo = circleWxInfoService.getOne(new QueryWrapper<CircleWxInfo>().eq("tenant_code", tenant));
        String appid = circleWxInfo.getAppid();
        String secret = circleWxInfo.getSecret();
        WxQr wxQr = new WxQr();
        MultipartFile file = wxQr.getminiqrQrTwo2(id,wxQr.getAccessToken(appid, secret).get("access_token").toString(), request);
        Map<String, Object> upResult = fastfileService.uploadFile("yctk-1256675456", file);
        return R.ok(upResult.get("kpath"));
    }



}
